#!/usr/bin/python
# -*- coding: utf-8 -*-

from flask import request, jsonify
from flask_restful import Resource
from manager.models import Account, AccountSchema, GatePair
from gate import gateManager
from manager import gateDao

accounts_schema = AccountSchema(many=True)
account_schema = AccountSchema()

class AccountResource(Resource):

    def post(self, api_name):

        json_data = request.get_json(force=True)

        if api_name == 'register':
            new_account = Account()
            new_account.__dict__.update(json_data)
            if new_account.account_name is None or new_account.password is None:
                return {'status': 'fail', 'message': '参数错误'}, 400

            old_account = Account.query.filter(Account.account_name == new_account.account_name).first()
            if old_account is not None:
                return {'status': 'fail','message': '该用户已注册'}, 400

            isSuccess = gateDao.insert(new_account)
            if isSuccess:
                return {'status': 'success', 'message': '注册成功'}, 201
            else:
                return {'status': 'fail', 'message': '注册失败'}, 201
        elif api_name == 'login':
            new_account = Account()
            new_account.__dict__.update(json_data)
            if new_account.account_name is None or new_account.password is None:
                return {'status': 'fail','message': '参数错误'}, 400

            old_account = Account.query.filter(Account.account_name == new_account.account_name).first()
            if old_account is not None:
                return {'status': 'fail','message': '无此用户'}, 200
            elif not old_account.password == new_account.password:
                return {'status': 'fail','message': '密码错误'}, 200
            else:
                return {'status': 'success', 'message': '登录成功', 'data':account_schema.dump(old_account).data}, 201

        else:
            return {'status': 'fail', 'message': '参数错误'}, 400




